package com.buddha.api.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.buddha.api.common.Result;
import com.buddha.api.entity.Files;
import com.buddha.api.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private IFileService iFileService;

    @Value("${files.upload.path}")
    private String fileUploadPath;
    //@Value("${files.download.url}")
    private String baseUrl = "http://101.43.12.19:8082";

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        //  定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUuid =  uuid + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUuid);
        //  判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        if(!uploadFile.getParentFile().exists()){
            uploadFile.getParentFile().mkdirs();
        }


        String url ;
        file.transferTo(uploadFile);
        String md5 = SecureUtil.md5(uploadFile);
        Files fileByMd5 = getFileByMd5(md5);
        if(fileByMd5 != null){
            url=fileByMd5.getFUrl();
            uploadFile.delete();
        }else{
            url= baseUrl+"/file/"+fileUuid;
            Files saveFile = new Files();
            saveFile.setFName(originalFilename);
            saveFile.setFType(type);
            saveFile.setFSize(size/1024);
            saveFile.setFUrl(url);
            saveFile.setFMd5(md5);
            iFileService.save(saveFile);
        }

        return Result.success(url);
    }

    @GetMapping("/{fileUuid}")
    public void download(@PathVariable String fileUuid, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识查找文件
        File downFile = new File(fileUploadPath + fileUuid);
        ServletOutputStream outputStream = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUuid,"UTF-8"));
        response.setContentType("application/octet-stream");

        outputStream.write(FileUtil.readBytes(downFile));
        outputStream.flush();
        outputStream.close();
    }

    //  md5查询
    private Files getFileByMd5(String md5){
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("f_md5",md5);
        Files one = iFileService.getOne(queryWrapper);
        return one;
    }
}
